import http.client
import re

from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views import View
from apps.users.models import User,Address
from django.http import JsonResponse,HttpResponseBadRequest
import json

# Create your views here.
"""
判断用户名是否重复的请求
前端:  当用户输入用户名之后，失去焦点，发送一个axios(ajax)请求
后端: 
    请求:接受用户名
    业务逻辑：
    效应  JSON
        {code:0,count:0/1,errmsg:0k}
    
"""


class UernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})


class RegisterView(View):
    def post(self, request):
        # 接受请求
        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)
        # 获取数据
        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')
        # 验证数据
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match('[a-zA-Z0-9_-]{5,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名不满足规则'})
        # 数据入库
        """user=User(username=username,password=password,mobile=mobile)
        user.save()"""
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        login(request, user)
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class LoginView(View):
    def post(self, request):
        # 接收数据
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        # 验证数据
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 验证用户名和密码是否正确

        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})

        # session
        login(request, user)
        # 判断是否记住登录
        if remembered is not None:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)
        # 返回响应

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', username, max_age=30 * 60 * 60)
        return response


class LogoutView(View):
    def delete(self, request):
        logout(request)
        response = JsonResponse({'code': 200, 'errmsg': 'ok'})
        response.delete_cookie('username')


class CenterView(LoginRequiredMixin, View):
    def handle_no_permission(self):
        return JsonResponse({'code': 400, 'errmsg': '未登录'})

    def get(self, request):
        info_data = {
            'username': request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_active': request.user.email_active,
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})


class EmailView(LoginRequiredMixin, View):
    def put(self, request):
        data = json.loads(request.body.decode())
        email = data.get('email')
        user = request.user
        from celery_tasks.sms.tasks import celery_send_email
        title = '美多商城激活邮件'
        message = ""
        from utils.tools import encrypt
        data = {'id': request.user.id}
        id = encrypt(data)
        html_message = "点击按钮进行激活<a href='http://www.meiduo.site:8080/success_verify_email.html?token=%s'>激活</a>" % id
        recipient_list = ['2230053483@qq.com']
        celery_send_email.delay(title=title, message=message, html_message=html_message, recipient_list=recipient_list)
        user.email = email
        user.save()
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

class AddressCreateView(LoginRequiredMixin,View):
    def post(self,request):
        data=json.loads(request.body.decode())
        receiver=data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user

        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return  HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return HttpResponseBadRequest('参数mobile有误')

        try:
            address=Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            address_dict={
                'id':address.id,
                'title':address.title,
                'receiver':address.receiver,
                'province':address.province.name,
                'city':address.city.name,
                'district':address.district.name,
                'place':address.place,
                'mobile':address.mobile,
                'tel':address.tel,
                'email':address.email
            }
            return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})
        except:
            return JsonResponse({'code':400, 'errmsg': '未知错误','address':'none'})

class AddressView(View):
    def get(self,request):
        user=request.user
        addresses=Address.objects.filter(user=user,is_deleted=False)
        addresses_list=[]
        for address in addresses:
            addresses_list.append({
                'id':address.id,
                'title':address.title,
                'receiver':address.receiver,
                'province':address.province.name,
                'city':address.city.name,
                'district':address.district.name,
                'place':address.place,
                'mobile':address.mobile,
                'tel':address.tel,
                'email':address.email
            })
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'addresses':addresses_list,
            'default_address':user.default_address
        })
